export default {
	// 为当前模块开启命名空间
	namespaced: true,
	// 模块的 state 数据
	state: () => ({
		// 购物车的数组，用来存储购物车中每个商品的信息对象
		// 每个商品的信息对象，都包含如下 6 个属性：
		// { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
		cart: JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	// 模块的 mutations 方法
	mutations: {
		// 将购物车中的数据持久化存储到本地
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		//加入购物车
		addToCart(state, goods) {
			const findResult = state.cart.find((x) => x.goods_id === goods.goods_id)
			if (!findResult) {
				state.cart.push(goods)
			} else {
				findResult.goods_count++
			}
			// 通过 commit 方法，调用 m_cart 命名空间下的 saveToStorage 方法
			this.commit('m_cart/saveToStorage')
		},
		//更新购物车中商品的勾选状态
		updateGoodsState(state, goods) {
			const findResult = state.cart.find((x) => x.goods_id === goods.goods_id)
			if (findResult) {
				findResult.goods_state = goods.goods_state
				this.commit('m_cart/saveToStorage')
			}
		},
		//根据商品id更新购物车中商品数量
		updateGoodsNum(state, goods) {
			const findResult = state.cart.find((x) => x.goods_id === goods.goods_id)
			if (findResult) {
				findResult.goods_count = goods.goods_count
				this.commit('m_cart/saveToStorage')
			}
		},
		//根据商品id移除商品
		removeGoodsById(state, goods) {
			state.cart = state.cart.filter((x) => x.goods_id !== goods.goods_id)
			this.commit('m_cart/saveToStorage')
		},
		//更新所有商品状态
		updateAllGoodsState(state,isAll){
			state.cart.forEach(item=>item.goods_state=!isAll)
			this.commit('m_cart/saveToStorage')
		}
	},
	// 模块的 getters 属性
	getters: {
		//加入购物车的商品数量
		checkedCount(state) {
			let c = 0
			// 循环统计商品的数量，累加到变量 c 中
			state.cart.forEach(
				(goods) => {
					if (goods.goods_state == true) {
						c += goods.goods_count
					}
				}
			)
			return c
		},
		//计算购物车商品总价
		totalPrice(state) {
			let t = 0;
			state.cart.forEach(
				(goods) => {
					if (goods.goods_state == true) {
						t += goods.goods_count * goods.goods_price
					}
				}
			)
			return t
		},
		//计算商品数量
		total(state) {
			let count = state.cart.reduce((c, item) =>c+item.goods_count ,0)
			return count
		}
		
	}
}